var commonUtil = require("../../../utils/commonUtil.js")
var globalData = getApp().globalData;
var httpsUrl = globalData.httpsUrl;
var imgUrl = globalData.imgUrl;
Page({
  data: {
    imgUrl: imgUrl,
    openid: '',
    balanceCg: '',
    hiddenFlag4: true,
    hiddenFlag5: true,
    couponzs: "选择劵",//劵抵扣展示
    cardzs: "选择卡",//卡抵扣展示
    total: "0.00",//需要支付的金额
    totalMoney:"0.00",//总计
    orderNo: '',//订单id
    payGoods:[],
    cards:[],//卡列表
    coupons:[],//劵列表
    couponCode:"",
    memberCardCode:"",
    deliveryType:1,//2：快递配送（选择地址）
  },

  //加载商品 
  loadData:function(){
    var that = this;
    let payGoods = wx.getStorageSync(globalData.payGoods);
    this.setData({ payGoods: payGoods})
    this.total();
    this.voucher();//加载可用卡，劵
    this.deliveryType();
    this.morenAddress();
  },
  //计算总金额
  total: function () {
    let total = 0.00;
    let list = this.data.payGoods;
    let goods = [];
    if (list != undefined && list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        let good = new Object();
        good.code = list[i].code;
        good.num = list[i].count;
        goods = goods.concat(good);
      }
    }
    let that = this;
    let params = new Object();
    params.goodsList = goods;
    if (!commonUtil.isEmpty(this.data.couponCode)) {
      params.couponCode = this.data.couponCode;
    }
    if (!commonUtil.isEmpty(this.data.memberCardCode)) {
      params.memberCardCode = this.data.memberCardCode;
    }
    that.setData({ params: params});
    console.log("合计param:" + JSON.stringify(params));
    let openId = wx.getStorageSync("openidKey");
    commonUtil.showLoading("稍等...");
    wx.request({
      header: { "openId": openId, },
      url: httpsUrl + "/order/payMoney",
      dataType: "json",
      method: "POST",
      data: params,
      success: function (res) {
        commonUtil.hideLoading();
        res = res.data;
        console.log("合计：" + JSON.stringify(res));
        if (res.result == 0) {
          that.setData({ total: res.data.cashPayMoney.toFixed(2) })
          that.setData({ totalMoney: res.data.totalMoney.toFixed(2) })
        }
      }
    })
  },
  //提交订单
  submitOrder: function () {
    var that = this;
    let total = this.data.total;
    let params = this.data.params;
    if (this.data.deliveryType == 2){
      let addressInfo = this.data.addressInfo;
      if (addressInfo != undefined && addressInfo != null && addressInfo != '') {
        params.addressId = addressInfo.id;
      }else{
        wx.showModal({title: '提示',content: '请选择地址',})
        return;
      }
    }
    console.log("订单提交参数" + JSON.stringify(params));
    commonUtil.showLoading("提交中...");
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/json" },
        url: httpsUrl + "/order/subBuyGoods",
        dataType: "json",
        method: "POST",
        data: params,
        success: function (res) {
          commonUtil.hideLoading();
          console.log("提交订单返回:"+JSON.stringify(res));
          res = res.data;
          if (res.result == 0) {
            that.setData({ orderNo: res.data })
            that.goPay();
            //that.paySuccess();
          }else {
            commonUtil.showModal(res.msg);
          }
        }
      })
  },
  //获取openid
  goPay: function () {
    let total = this.data.total;//合计为0，跳过在线支付
    if (total > 0){
      var that = this;
      wx.login({
        success: function (res) {
          wx.showLoading({ title: '请稍等...', })
          wx.request({
            header: { "content-Type": "application/x-www-form-urlencoded" },
            url: httpsUrl + "/wechat/getOpenId",
            dataType: "json",
            method: "POST",
            data: { "code": res.code, "agentCode": globalData.agentCode},
            success: function (res) {
              wx.hideLoading();
              res = res.data;
              console.log("获取openid返回:" + JSON.stringify(res));
              if (res.result == 0) {
                let data = JSON.parse(res.data);
                console.log(data.openid);
                that.setData({ openid: data.openid })
                that.pay();
              } else {
                console.log("获取openid失败：" + res.msg);
              }
            }
          })
        }
      })
    } else if (total == 0) {
      this.paySuccess();
    }
  },
  //支付
  pay: function () {
    let that = this;
    let params = new Object();
    params.orderNo = this.data.orderNo;
    params.openid = this.data.openid;
    console.log(JSON.stringify(params));
    commonUtil.showLoading("去支付...");
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/order/payParam",//统一下单返回支付参数
      dataType: "json",
      method: "POST",
      data: params,
      success: function (res) {
        commonUtil.hideLoading();
        console.log("统一下单返回"+JSON.stringify(res));
        res = res.data;
        if (res.result == 0) {
          var data = res.data;
          //调起支付
          wx.requestPayment(
            {
              'timeStamp': data.timeStamp,
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': 'MD5',
              'paySign': data.paySign,
              'success': function (res) {
                console.log("支付调起成功");
                that.paySuccess();
              },
              'fail': function (res) {
                console.log("用户取消支付");
                wx.switchTab({
                  url: '../orderList/orderList',
                })
               },
              'complete': function (res) { }
            })
        } else {
          commonUtil.showModal("支付失败：" + res.msg);
        }
      }
    })
  },
  
  paySuccess:function(){
    wx.navigateTo({
      url: '../paySuccess/paySuccess',
    })
  },
  
  //数量操作
  addCount:function(){
    this.setData({ count:this.data.count + 1 })
    this.setTotal();
  },
  subtract: function () {
    if(this.data.count > 1){
      this.setData({ count: this.data.count - 1 })
      this.setTotal();
    }
  },
  //优惠劵板块
  juanModal: function () {
    if (this.data.hiddenFlag4 == true){
      //this.voucher();
    }
    this.setData({ hiddenFlag4: !this.data.hiddenFlag4, });
  },
  //我的劵。卡列表
  voucher: function (){
    let list = this.data.payGoods;
    let goods = [];
    if (list != undefined && list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        let good = new Object();
        good.code = list[i].code;
        good.num = list[i].count;
        goods = goods.concat(good);
      }
    }
    let that = this;
    let params = new Object();
    params.goodsList = goods;
    console.log("param:"+JSON.stringify(params));
    let openId = wx.getStorageSync("openidKey");
    commonUtil.showLoading("稍等...");
    wx.request({
      header: { "openId": openId, },
      url: httpsUrl + "/order/cardCouponList",
      dataType: "json",
      method: "POST",
      data: params,
      success: function (res) {
        commonUtil.hideLoading();
        console.log("劵卡：" + JSON.stringify(res));
        res = res.data;
        if (res.result == 0) {
          that.setData({ coupons: res.data.coupon, cards: res.data.card })
          // console.log("res.data.coupon.length:"+res.data.coupon.length);
          if (res.data.coupon.length == 0){
            that.setData({ couponzs:"无可使用劵"})
          }
          if (res.data.card.length == 0) {
            that.setData({ cardzs: "无可使用卡" })
          }
        }
      }
    })
  },
  //选择劵
  selectVoucher:function(e){
    let id = e.currentTarget.id;
    let list = this.data.coupons;
    let row = list[id];
    this.setData({ couponzs: row.discountRule, couponCode: row.code })
    this.total();
    this.setData({ hiddenFlag4: !this.data.hiddenFlag4, });
  },
  card: function () {
    if (this.data.hiddenFlag4 == true) {
      //this.voucher();
    }
    this.setData({ hiddenFlag5: !this.data.hiddenFlag5, });
  },
  selectCard:function(e){
    let id = e.currentTarget.id;
    let list = this.data.cards;
    let row = list[id];
    this.setData({ cardzs: row.discountRule, memberCardCode: row.code })
    this.total();
    this.setData({ hiddenFlag5: !this.data.hiddenFlag5, });
  },
  deliveryType: function () {
    let list = this.data.payGoods;
    if (list != undefined && list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].deliveryType==2){
          this.setData({ deliveryType:2})
          return;
        }
      }
    }
  },
  morenAddress:function(){
      var that = this;
      let openId = wx.getStorageSync("openidKey");
      commonUtil.showLoading("加载中...");
      wx.request({
        url: httpsUrl + "/memberAddress/getDefaultAddress",
        header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
        dataType: "json",
        method: "GET",
        // data: params,
        success: function (res) {
          commonUtil.hideLoading();
          res = res.data;
          console.log("默认地址:" + JSON.stringify(res));
          if (res.result == 0) {
            that.setData({ addressInfo: res.data })
          }
        }
      })
  },
  goAddress:function(){
    wx.setStorageSync("returnAddress", 1);
    wx.navigateTo({url: '../../user/myAddress/myAddress',})
  },
  getAddress:function(){
    let returnAddress = wx.getStorageSync("returnAddress");
    if (returnAddress == 1) {
      let addressInfo = wx.getStorageSync("addressInfo");
      console.log(addressInfo);
      if (addressInfo != undefined && addressInfo != null && addressInfo != '') {
        this.setData({ addressInfo: addressInfo });
      }
    }
  },
  onLoad: function (options) {
    wx.setStorageSync("returnAddress", 0);
    this.loadData();
  },
  onShow: function () {
    this.getAddress();
  },
})